package com.shuql.zklock.impl;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.concurrent.CountDownLatch;

public class ZKDistrbuteLock extends AbstrackLock {

    private ZkClient zkClient = null;

    public ZKDistrbuteLock(String path, int port) {
        zkClient = new ZkClient(path + ":" + port);
    }

    private CountDownLatch countDownLatch = null;

    /**
     * 尝试创建节点进行加锁
     *
     * @param path zk节点路径
     * @return
     */
    @Override
    public boolean tryLock(String path) {
        try {
            zkClient.createEphemeral(path);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 等待创建节点加锁
     *
     * @param path zk节点路径
     */
    @Override
    public void waitLock(String path) {
        IZkDataListener iZkDataListener = new IZkDataListener() {
            public void handleDataChange(String s, Object o) throws Exception {

            }

            public void handleDataDeleted(String s) throws Exception {
                if (countDownLatch != null) {
                    countDownLatch.countDown();
                }
            }
        };

        //监听
        zkClient.subscribeDataChanges(path, iZkDataListener);

        //节点存在，说明已经被上锁,需等待
        if (zkClient.exists(path)) {
            countDownLatch = new CountDownLatch(1);
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //取消监听
        zkClient.unsubscribeDataChanges(path, iZkDataListener);
    }

    /**
     * 删除节点释放锁
     *
     * @param path zk节点路径
     */
    public void unLock(String path) {
        if (zkClient != null) {
            zkClient.delete(path);
        }
    }
}
